import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;

import leesoft.configuration.core.DBToolKit;
import leesoft.configuration.core.RowHandler;
import leesoft.configuration.databeans.DataSource;
import leesoft.configuration.databeans.Integration;
import leesoft.configuration.xmlconfig.Configuration;
import leesoft.tibmigrator.DBDetector;


public class Launcher {

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		
		// TODO Auto-generated method stub
		System.out.println("Welcome To Use TIB Migration Tool v1.0");
		System.out.println("======================================");
		System.out.println("Initializing configuration file...");
		Configuration xmlconfig=new Configuration("config.xml");
		if(xmlconfig==null){
			System.out.println("failed");
			return;
		}
		System.out.println("done!");
		System.out.println("Start To Integrate:");
		for(Integration integration:xmlconfig.getIntegrations()){
			if(integration.isDisabled())
				continue;
			out("this version is going to use output file, the file will be write to "+integration.getOutputfile());
			out("from sourceDS:"+integration.getSourceDS()+" to targetDS:"+integration.getTargetDS());
			
			DBToolKit dbtk=new DBToolKit(); 
			DataSource sourceDS=xmlconfig.getDS(integration.getSourceDS());
			dbtk.open(sourceDS);
			File file=new File(integration.getOutputfile());
			FileWriter writer=new FileWriter(file,true);
			RowHandler rh=new RowHandler(integration,writer);
			integration.pluginStart();
			String query=integration.beforePluginExecute(integration.getQuery());
			dbtk.executeOn(query, rh);
			integration.pluginEnd();
			writer.close();
			dbtk.close();
		}
		
//		DBDetector detector=new DBDetector();
//		
//		System.out.println("detecting the connection to the resource database...");
//		if(detector.detecting(xmlconfig.getSourceConnString(), xmlconfig.getSourceDriver(),
//				xmlconfig.getSourceUsername(), xmlconfig.getSourcePassword())==false){
//			System.out.println("failed");
//			return;
//		}
//		System.out.println("done!");
//		
//		System.out.println("detecting the connection to the target database...");
//		if(detector.detecting(xmlconfig.getTargetConnString(), xmlconfig.getTargetDriver(),
//				xmlconfig.getTargetUsername(), xmlconfig.getTargetPassword())==false){
//			System.out.println("failed");
//			return;
//		}
		System.out.println("done!");
		
	}
	private static void out(String output){
		System.out.println(output);
	}

}
